package controllers;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import models.Entities;
import models.Invitation;
import models.Organization;
import models.Permission;
//import models.Permission;
import models.User;
import play.db.jpa.JPA;
import play.mvc.Controller;

public class Invitations extends Controller {
	public static long entityId;
	public static long organizationId;

	/**
	 * shows all users to choose from to send invitations to
	 * 
	 * @param entId
	 *            it takes the entity id so that it could be used when calling
	 *            the method sending invitations
	 * 
	 * @author Mai Selwanes
	 */
	public static void showAllUsers(long entityGivenId) {
		
		entityId = (long)entityGivenId;
		boolean empty = false;
		Entities entity = Entities.findById(entityId);
		if (entity ==null) System.out.println("entity null");
		String idString = session.get("userId");
		long otherId = Long.parseLong(idString);
		User user = User.findById(otherId);
		List<User> userList = User.findAll();
		System.out.println(entityGivenId);
		List<User> entityOrganizers = entity.entityOrganizers;

		for (int i = 0; i < userList.size(); i++) {
			if (userList.get(i) == user)
				userList.remove(i);
		}
		for (int i = 0; i < userList.size(); i++) {
			if (entity.organization.lead.id == userList.get(i).id)
				userList.remove(i);

		}
		for (int i = 0; i < userList.size(); i++) {
			if (userList.get(i).name.equals("Anonymous"))
				userList.remove(i);
		}
		for (int i = 0; i < userList.size(); i++) {
			if (userList.get(i).name.equals("admin"))
				userList.remove(i);
		}

		for (int i = 0; i < userList.size(); i++) {

			for (int j = 0; j < entityOrganizers.size(); j++) {
				if (userList.get(i) == entityOrganizers.get(j)) {
					userList.remove(i);
				}

			}

		}

		if (userList.isEmpty()) {
			empty = true;
			render(userList, entityId, empty);
		}

		render(userList, entityId, empty);
	}

	/**
	 * a method that renders the html page for showing only the users that are
	 * not in that entity: this is done by a query to choose from to send
	 * invitations to
	 * 
	 * 
	 * @author Mai Selwanes
	 */
	public static void showUsersNotInOrg(long organizationID) {
		organizationId = organizationID;
		System.out.println(organizationId);

		Organization organization = Organization.findById(organizationId);

		System.out.println(organizationId);
		boolean empty = false;
		List<User> all = User.findAll();
		List<User> inOrganization = organization.orgMembers;
		List<User> notInOrganization = new ArrayList();
		for (int i = 0; i < all.size(); i++) {
			boolean userInOrganization = false;
			for (int j = 0; j < inOrganization.size(); j++) {

				if (all.get(i).id == inOrganization.get(j).id) {
					userInOrganization = true;
				}
			}
			if (userInOrganization == false) {
				User user = User.findById(all.get(i).id);
				notInOrganization.add(user);
			}
		}

		for (int i = 0; i < notInOrganization.size(); i++) {
			if (notInOrganization.get(i).name.equals("Anonymous"))
				notInOrganization.remove(i);

		}
		for (int i = 0; i < notInOrganization.size(); i++) {
			if (organization.lead.id == notInOrganization.get(i).id)
				notInOrganization.remove(i);

		}
		for (int i = 0; i < notInOrganization.size(); i++) {

			if (notInOrganization.get(i).name.equals("admin"))
				notInOrganization.remove(i);

		}
		if (notInOrganization.isEmpty()) {
			empty = true;
			render(notInOrganization, organizationId, empty);
		}

		render(notInOrganization, organizationId, empty);
	}

	/**
	 * a method that renders the html page for confirming that the invitations
	 * have been sent to the selected users from the check box
	 * 
	 * 
	 * @author Mai Selwanes
	 */

	public static void selectAllOrg() {

		Entities entity = Entities.findById(entityId);
		Long organizationId= entity.organization.id;
		String[] param = params.getAll("box");
		ArrayList<User> users = new ArrayList();
		boolean didNotSelect = false;
		if (param == null)
			didNotSelect = true;
		else {
			for (int i = 0; i < param.length; i++) {

				String idRetrieve = "";
				for (int x = 0; x < param[i].length(); x++) {
					if (param[i].charAt(x) >= '0' && param[i].charAt(x) <= '9') {
						idRetrieve += param[i].charAt(x);
					}
				}
				Long id = Long.parseLong(idRetrieve);
				User us = User.findById(id);
				users.add(us);
			}
			String id_string = session.get("userId");
			Long id = Long.parseLong(id_string);
			User user = User.findById(id);
			// Long userId = (long) 5;
			// Long entIdExample = (long) 1;

			entity.sendInviteToBeOrganizer(user, users);

		}
		render(entityId, didNotSelect,organizationId);

	}

	/**
	 * a method that renders the html page for confirming that the invitations
	 * have been sent to the selected users from the check box
	 * 
	 * @param entId
	 *            it takes the entity id so that it could be used when calling
	 *            the method sending invitations
	 * 
	 * @author Mai Selwanes
	 */
	public static void selectAllId() {
		System.out.println(organizationId);
		Organization organization = Organization.findById(organizationId);

		
		Long organizationId= organization.id;
		String[] param = params.getAll("box");
		ArrayList<User> users = new ArrayList();
		boolean didNotSelect = false;
		if (param == null)
			didNotSelect = true;
		else {
			for (int i = 0; i < param.length; i++) {
				String idRetrieve = "";
				for (int x = 0; x < param[i].length(); x++) {
					if (param[i].charAt(x) >= '0' && param[i].charAt(x) <= '9') {
						idRetrieve += param[i].charAt(x);
					}
				}
				Long id = Long.parseLong(idRetrieve);
				User us = User.findById(id);
				users.add(us);
			}
			String id_string = session.get("userId");
			Long id = Long.parseLong(id_string);
			User user = User.findById(id);
			System.out.println(organizationId);
			organization.sendInviteToBeIdeaDeveloper(user, users);
		}
		render(organization, didNotSelect, organizationId);
	}

	/**
	 * a method that renders the html page for showing all invitations of the
	 * user
	 * 
	 * @author Mai Selwanes
	 */
	public static void showInvitations() {
		String id_string = session.get("userId");
		Long id = Long.parseLong(id_string);
		User user = User.findById(id);
		List<Invitation> invitation = user.invitations;
		boolean empty = false;
		if (invitation.isEmpty())
			empty = true;
		render(invitation, user, empty);
	}

	/**
	 * 
	 * takes the invitation id renders the html page for showing accepting
	 * invitation of the user
	 * 
	 * a method that renders the html page for showing accepting invitation of
	 * the user
	 * 
	 * 
	 * @see accept.html page contains a message to the user that he successfully
	 *      accepted the invitation
	 * 
	 * @param invId
	 *            the id of the invitation that the user would accept on
	 * 
	 * @author Noha wafa
	 */
	public static void accept(long invId) {
		Long id = Long.parseLong(session.get("userId"));
		User user = User.findById(id);
		Invitation inv = Invitation.findById(invId);
		long EntId = inv.entityOrOrgId;
		System.out.println(inv.type);
		Entities entity = Entities.findById(EntId);
		Organization organization = entity.organization;

		if (inv.type == "organizer") {
			if (user.userPermissionInOrganization(user.id, organization.id) != null
					|| user.userPermissionInEntity(user.id, organization.id,
							entity.id) != null) {
				Permission permissionOrg = user.userPermissionInOrganization(
						user.id, organization.id);
				Permission permissionEnt = user.userPermissionInEntity(user.id,
						organization.id, entity.id);

				if (permissionOrg.aUserType.equals("ideaDeveloper")) {
					permissionOrg.aUserType = "organizer";
					permissionOrg.save();
					Permission permissionInEntity = new Permission("organizer",
							organization, user, entity);
					permissionInEntity.save();
					entity.entityOrganizers.add(user);
					entity.save();

				} else {
					if (permissionOrg.aUserType.equals("organizer")
							&& permissionEnt.aUserType.equals("organizer")) {
						System.out.println("he is alrady org");
					}
				}
			} else {
				Permission permissionInOrg = new Permission("organizer",
						organization, user, null);
				permissionInOrg.save();
				Permission permissionInEntity = new Permission("organizer",
						organization, user, entity);
				permissionInEntity.save();
				entity.entityOrganizers.add(user);
				organization.orgMembers.add(user);
				user.organization.add(organization);
				organization.save();
				entity.save();
				user.save();
			}

			for (int j = 0; j < entity.organization.blockedUsers.size(); j++) {
				if (user.equals(entity.organization.blockedUsers.get(j))) {
					entity.organization.blockedUsers.remove(user);
					entity.save();
					user.save();

				}

			}
		} else if (inv.type == "ideaDeveloper") {
			Organization org = Organization.findById(inv.entityOrOrgId);
			org.orgMembers.add(user);
			user.organization.add(org);
			Permission perm = new Permission("ideaDeveloper", org, user, null)
					.save();

			for (int i = 0; i < org.blockedUsers.size(); i++) {
				if (user.equals(org.blockedUsers.get(i))) {
					org.blockedUsers.remove(user);
				}
			}
			org.save();
			user.save();
		}
		inv.delete();
		String accept = user.name + " you accepted the Invitation ";

		render(user, accept, EntId);

	}

	/**
	 * 
	 * renders the html page for showing rejecting invitation of the user
	 * 
	 * 
	 * @see reject.html page contains a message to the user that he successfully
	 *      rejected the invitation
	 * 
	 * @param invId
	 *            the id of the invitation that the user would reply on
	 * 
	 * @author Noha wafa
	 */
	public static void reject(Long invId) {
		String idString = session.get("userId");
		Long id = Long.parseLong(idString);
		User user = User.findById(id);
		Invitation inv = Invitation.findById(invId);
		System.out.println(invId);
		inv.delete();
		String reject = user.name + " you rejected the Invitation";
		render(user, reject);
	}

}